<?php
session_start();

if ( !$_SESSION['manager'] )
{
    header('Location: index.php');
    exit();
}
else
{
    require_once('inc/config.db.php');
    require_once('core/core.php');

    $crm = new LocalCRM;

    $doc_path = Path_files;

    if ( !is_dir($doc_path) )
    {
	die(sprintf('Директория \'%s\' не существует!',$doc_path));
    }

    for ( $i=0;$i<sizeof($_FILES['document_file']);$i++ )
    {
	if ( $_FILES['document_file']['size'][$i]==0 ) { continue; }

	$dir = sprintf('%s/%04d',$doc_path,$_POST['account_id']);

	if ( !is_dir($dir) && !mkdir($dir) )
	{
	    die('Невозможно создать директорию для хранения документов!');
	}

	$file = preg_replace('/(.+)\.(.+)$/',uniqid(true).'.$2',$_FILES['document_file']['name'][$i]);
	$path = sprintf('%s/%s',$dir,strtolower($file));

	switch ( $_POST['type'][$i] )
	{
	    case	'inv_region':	{ $type = 'inv_region'; break; }
	    case	'inv_inlain':	{ $type = 'inv_inlain'; break; }
	    default:			{ $type = 'ordinary'; }
	}

	if ( move_uploaded_file($_FILES['document_file']['tmp_name'][$i],$path) )
	{
	    $query = sprintf(
				'INSERT INTO `document` (`account_id`,`document_num`,`document_name`,`document_date`,`type`,`filename`,`size`,`path`)'
				.' VALUES (%d,\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',%d,\'%s\')',
				$_POST['account_id'],
				$_POST['document_num'][$i],
				$_POST['document_name'][$i],
				$_POST['document_date'][$i],
				$type,
				$_FILES['document_file']['name'][$i],
				$_FILES['document_file']['size'][$i],
				sprintf('%04d/%s',$_POST['account_id'],$file)
			    );
	    mysql_query($query) || unlink($path);
	}
	else
	{
	    die('can\'t move file');
	}

	if ( mysql_error() ) { die(mysql_error()); }
    }

    header('Location: '.$_SERVER['HTTP_REFERER'].($type!='ordinary'?'#invoice':'#document'));
}
?>
